import axios from 'axios'
import config from "@/config/index.js";
import utils from "@/utils/utils.js";
import useCounterStore from "@/store/counter";
import useUserStore from '@/store/modules/user'
import { getToken } from '@/utils/auth'

const request = (options = {}) => {
  options.headers = {}
  if (!options.headers) options.headers = { "content-type": "application/json", }

  let ycAdminParams = localStorage.getItem("ycAdminParams");
  ycAdminParams = JSON.parse(ycAdminParams)
  if (ycAdminParams && ycAdminParams.token) {
    options.headers['Authorization'] = `Bearer ${ycAdminParams.token}`
  }

  return new Promise((resolve, reject) => {
    let obj = {
      url: config.baseUrl + options.url || '',
      method: options.method.toLocaleUpperCase() || 'GET',
      headers: options.headers || {}
    }
    switch (options.method) {
      case "get":
        obj.params = options.data || {}
        break;
      case "post":
        obj.data = options.data || {}
        break;
      default:
        break;
    }
    axios(obj).then(async data => {
      let code = data.data.code
      if (code == 200) {
        resolve(data.data.data);
      } else if (code == 401) { //登录过期
        utils.showToast(data.data.msg, 0)
        await useUserStore().logOut()
        let pathname = window.location.pathname
        setTimeout(() => {
          //window.location.replace(`/login?redirect=${pathname}`)
        }, 1500);
      }
      else {
        utils.showToast(data.data.msg, 0)
        reject(data.data.msg)
      }
    }).catch(error => {
      utils.showToast(error, 0)
      reject(error)
    })
  });
}

const get = (url, data, options = {}) => {
  options.method = 'GET';
  options.data = data;
  options.url = url;
  return request(options)
}

const post = (url, data, options = {}) => {
  options.method = 'POST';
  options.data = data;
  options.url = url;
  return request(options)
}


export default {
  request,
  get,
  post
}
